<?php
namespace Modules\Activity\Entities\EggLottery;

use Modules\Activity\Entities\BaseActivityModel;
use Illuminate\Database\Eloquent\Builder;
use Modules\Asset\Entities\Package;
use ThrowException;
use Setting;

// 一翻赏
class Activity extends BaseActivityModel
{
    protected $table = 'egg_lottery';

    public $activityType = 'egg_lottery';
    public $activityTypeText = '扭蛋机';

    // protected $guarded = ['union_status', 'union_status_text', 'type_text'];

    // protected $appends = ['union_status', 'union_status_text'];

    protected $casts = [
        'images' => 'json',
        'detail_images' => 'json',
    ];

    public function getType($type) 
    {
        $map = [
            'base_sku_type' => 'egg_lottery',
            'node_type' => 'egg_lottery'
        ];

        return @$map[$type];
    }

    // 
    public function getNodeEntity()
    {
        return $this;
    }

    // 所有sku
    public function skus()
    {
        return $this->hasMany('\Modules\Activity\Entities\EggLottery\Sku', 'activity_id')->orderBy('list_weight', 'desc');
    }

    public function getOnStockSkus()
    {
        return $this->skus()->where('stock', '>', 0)->get();
    }

    // 抽出幸运sku
    public function pickLuckySkus($total, $user = NULL, $order = NULL, $options = [])
    {
        // 取哪一个福袋
        $skus = $this->getOnStockSkus();
        // $skus = $this->skus()->onStock()->where('stock', '>', 0)->get();

        $luckyList = pickLuckySkuMaps($skus, 'odds', $total);

        if (!$luckyList) {
            return null;
        }

        // 扣除库存
        if (!isset($options['add_sales']) || $options['add_sales']) {
            foreach ($luckyList as $skuMap) {
                if (!$skuMap['skuable']->addSales($skuMap['total'])) {
                   \Log::error('福袋抽盒库存不足 sku_id:' . $skuMap['skuable']->id);
                   ThrowException::Conflict('库存不足~');
                }
            }
        }

        return $luckyList;
    }

    // 试玩开sku
    public function pickLuckySkusForTry($total, $user = NULL, $order = NULL, $options = [])
    {
        $skus = $this->getOnStockSkus();

        // 虚拟库存
        $oddsTotal = $skus->sum('odds');
        $skus->each(function ($item) use ($oddsTotal) {
            $item->stock = 100;
            $item->odds = $oddsTotal - $item->odds;
        });

        // \Log::error($skus);

        $luckyList = pickLuckySkuMaps($skus, 'odds', $total);

        return $luckyList;
    }

    // 更新库存
    public function updateStock()
    {
        $this->update([
            'stock' => $this->skus()->sum('stock')
        ]);
    }


    // 检查sku库存
    public function checkSkuStock($total)
    {
        return $this->skus()->sum('stock') >= $total;
    }

    // 检查是否超出限制
    static public function checkSaleLimit($total)
    {
        $setting = @Setting::get('sys_fudai_sale_limit') ?: [];
        if (@$setting['is_limit_every_day'] && @$setting['limit_total_every_day']) {
            $limitEveryDay = $setting['limit_total_every_day'];

            $todaySales = Package::where('node_type', 'fudai')->whereIn('status', [0, 1])->where('source_type',  1)->whereDate('created_at', date('Y-m-d'))->sum('sku_total');

            if ($todaySales + $total > $limitEveryDay) {
                if ($todaySales >= $limitEveryDay) {
                    ThrowException::Conflict('福袋今日已达到销售上限~');
                }
                else {
                    ThrowException::Conflict('福袋今日还可销售' . ($limitEveryDay - $todaySales) . '个~');
                }
            }
        }
        return true;
    }
}
